package site.edody.dframe.rocketmq;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.apache.rocketmq.client.producer.DefaultMQProducer;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;

import java.util.Map;
import java.util.stream.Collectors;

/**
 * 配置RocketMQ
 */
@Configuration
public class MQProducerConfig {

    private final Logger logger = LoggerFactory.getLogger(MQProducerConfig.class);

    @Bean
//    @ConfigurationProperties(prefix = "dframe.rocketmq")
    public RocketMQProperties rocketMQProperties() {
        return new RocketMQProperties();
    }

    @Bean
    public Map<String, DefaultMQProducer> mqProducers(RocketMQProperties properties) {
        Map<String, RocketMQProperties.ProducerConfig> producerConfigs = properties.getProducers();
        return producerConfigs.entrySet().stream()
                .collect(Collectors.toMap(
                        Map.Entry::getKey,
                        entry -> createProducer(entry.getValue(), properties.getNameServer())
                ));
    }

    private DefaultMQProducer createProducer(RocketMQProperties.ProducerConfig config, String nameServer) {
        DefaultMQProducer producer = new DefaultMQProducer(config.getGroup());
        producer.setNamesrvAddr(nameServer);
        // 关键优化参数
        producer.setVipChannelEnabled(false); // 禁用 VIP 通道
        producer.setSendMsgTimeout(10000); // 增加超时时间
        producer.setRetryTimesWhenSendFailed(5); // 增加重试次数
        producer.setRetryAnotherBrokerWhenNotStoreOK(true); // 尝试其他 Broker
        try {
            producer.start();
            logger.info("Producer started: " + config.getGroup());
        } catch (Exception e) {
            throw new RuntimeException("Failed to start producer: " + config.getGroup(), e);
        }
        return producer;
    }
}